package com.poc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.poc.database.DatabaseManager;

public class Main {

    public static final int COLUMN_NUNIVELOTTO = 2;
    public static final int LIMIT = 1;

    public static void main(String[] args) throws SQLException {
	DatabaseManager databaseManager = DatabaseManager.getInstance();

	String sql = String.format("select * from %s", Table.OTTOBACIA_NIVEL_1.getName());
	String nunivelotto;
	ResultSet resultSet = databaseManager.execute(sql);
	ResultSet rios = null;
	int total, success;
	int corioIndex;
	boolean hasRows = false;
	HashMap<String, String> riosComBacia = new HashMap<String, String>();
	List<String> riosSemBacia = new ArrayList<String>();

	corioIndex = total = success = 0;

	// SQLs parametrizadas
	String parametrizedSelect = "select * from unificado where corio like '%s_%s' order by nuareabacc desc limit(%d)";
	String parametrizedUpdate = "update %s set nome = '%s' where nunivotto1 = '%s'";

	// System.out.println("Starting script...");
	long start = System.currentTimeMillis();

	while (resultSet.next()) {
	    nunivelotto = resultSet.getString(Main.COLUMN_NUNIVELOTTO);

	    // while(!hasRows && corioIndex < 1){
	    sql = String.format(parametrizedSelect, nunivelotto, corioIndex, Main.LIMIT);
	    rios = databaseManager.execute(sql);
	    hasRows = rios.next();
	    corioIndex++;
	    // }

	    if (hasRows) {
		success++;
		riosComBacia.put(nunivelotto, Utils.removeSpecialCaracters(rios.getString("noriocomp")));
	    } else {
		riosSemBacia.add(nunivelotto);
	    }
	    total++;
	    corioIndex = 0;
	    hasRows = false;
	}

	// System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
	// System.out.println("Starting updates...");

	for (String nivelOtto : riosComBacia.keySet()) {
	    sql = String.format(parametrizedUpdate, Table.OTTOBACIA_NIVEL_1.getName(), riosComBacia.get(nivelOtto), nivelOtto);

	    // System.out.println(sql);

	    databaseManager.executeUpdate(sql);
	}

	databaseManager.commit();

	// System.out.println(String.format("\nTotal %d - Sucess %d", total, success));
	// System.out.println("Elapsed time: " + (System.currentTimeMillis() - start));
    }
}
